package services

import (
	"errors"
	"fmt"
	"github.com/jassue/jassue-gin/app/common/request"
	"github.com/jassue/jassue-gin/app/models"
	"github.com/jassue/jassue-gin/global"
	"github.com/jassue/jassue-gin/utils"
	"gorm.io/gorm"
	"strconv"
)

type userService struct {
}

var UserService = new(userService)

// Login 登录
func (userService *userService) Login(params request.Login) (err error, user *models.User) {
	err = global.App.DB.Where("mobile = ?", params.Mobile).First(&user).Error
	if err != nil || !utils.BcryptMakeCheck([]byte(params.Password), user.Password) {
		err = errors.New("用户名不存在或密码错误")
	}
	return
}

// 获取用户信息
func (userService *userService) GetUserInfo(id string) (err error, user models.User) {
	intId, err := strconv.Atoi(id)
	err = global.App.DB.First(&user, intId).Error
	if err != nil {
		err = errors.New("数据不存在")
	}
	return
}

// 添加用户数据
func (userService *userService) AddUser(params request.Adduser) (err error) {

	return global.App.DB.Transaction(func(db *gorm.DB) error {

		var result = db.Where("mobile = ?", params.Mobile).Select("id").First(&models.User{})
		if result.RowsAffected != 0 {
			err = errors.New("手机号已存在")
			return err
		}

		user := models.User{Name: params.Name, Mobile: params.Mobile, Password: utils.BcryptMake([]byte(params.Password)),
			Realname: params.Realname, Email: params.Email}

		err = db.Create(&user).Error

		fmt.Println(user.ID.ID) //

		fmt.Printf("%+v\n", &user) //

		if len(params.RoleIds) == 0 {
			return nil
		}

		//containerInt

		//判断角色id是否存在 begin
		var Roles []models.Role
		db.Select("id").Find(&Roles, params.RoleIds)

		fmt.Println("-----1----")
		fmt.Printf("%+v\n", Roles)

		//set := make(map[uint]struct{}, len(Roles))

		var slices []interface{}
		for _, v := range Roles {
			slices = append(slices, v.ID.ID)
		}
		fmt.Printf("%+v\n", slices)

		for _, v := range params.RoleIds {
			ok := utils.In_array(v, slices)
			if !ok {
				fmt.Printf("%+v\n", v) //
				err = errors.New("params.RoleIds参数错误")
				db.Rollback()
				return err
			}
		}
		//判断角色id是否存在 end

		fmt.Println("-----1----")

		fmt.Printf("%+v\n", params.RoleIds)

		//user_roles 表添加数据
		TxErr := db.Delete(&[]models.UserRole{}, "model_id = ?", user.ID.ID).Error
		if TxErr != nil {
			return TxErr
		}
		var useAuthority []models.UserRole
		for _, v := range Roles {
			useAuthority = append(useAuthority, models.UserRole{
				UserId: user.ID.ID, RoleId: v.ID.ID,
			})
		}
		TxErr = db.Create(&useAuthority).Error

		if TxErr != nil {
			return TxErr
		}

		// 返回 nil 提交事务

		return nil
	})

}

// 编辑用户
func (userService *userService) EditUser(params request.Edituser) (err error) {

	return global.App.DB.Transaction(func(db *gorm.DB) error {

		var rt = db.Where("id=? ", params.Id).Select("id").First(&models.User{})
		if rt.RowsAffected == 0 {
			err = errors.New("该id数据不存在")
			return err
		}

		var result = db.Where("id=? and mobile <> ?", params.Id, params.Mobile).Select("id").First(&models.User{})
		if result.RowsAffected != 0 {
			err = errors.New("手机号已存在")
			return err
		}

		user := models.User{Name: params.Name, Mobile: params.Mobile, Password: utils.BcryptMake([]byte(params.Password)),
			Realname: params.Realname, Email: params.Email}

		//编辑数据
		db.Model(&user).Where("id = ?", params.Id).Updates(&user)

		fmt.Println(user.ID.ID) //

		fmt.Printf("%+v\n", &user) //

		if len(params.RoleIds) == 0 {
			//user_roles 表删除数据
			TxErr := db.Delete(&[]models.UserRole{}, "model_id = ?", params.Id).Error
			if TxErr != nil {
				return TxErr
			}
			return nil
		}

		//判断角色id是否存在 begin
		var Roles []models.Role
		db.Select("id").Find(&Roles, params.RoleIds)

		fmt.Printf("%+v\n", Roles)

		set := make(map[uint]struct{}, len(Roles))
		for _, v := range Roles {
			set[v.ID.ID] = struct{}{}
		}
		fmt.Printf("%+v\n", set)

		for _, v := range params.RoleIds {
			_, ok := set[v]
			if !ok {
				fmt.Printf("%+v\n", v) //
				err = errors.New("params.RoleIds参数错误")
				db.Rollback()
				return err
			}
		}
		//判断角色id是否存在 end

		fmt.Printf("%+v\n", params.RoleIds)

		//user_roles 表添加数据
		TxErr := db.Delete(&[]models.UserRole{}, "model_id = ?", params.Id).Error
		if TxErr != nil {
			return TxErr
		}
		var useAuthority []models.UserRole
		for _, v := range Roles {
			useAuthority = append(useAuthority, models.UserRole{
				UserId: params.Id, RoleId: v.ID.ID,
			})
		}
		TxErr = db.Create(&useAuthority).Error

		if TxErr != nil {
			return TxErr
		}

		// 返回 nil 提交事务

		return nil
	})

}

// 启用禁用
func (userService *userService) EditStatus(params request.EditStatus) (err error, user *models.User) {
	global.App.DB.Model(&user).Where("id = ?", params.Id).Update("status", params.Status)
	return nil, user
}

// 角色列表
func (userService *userService) GetUserList(params request.GetUserList) (err error, result []*models.UserList) {
	var page uint = params.Page - 1
	var keywords string = "%" + params.Keywords + "%"

	global.App.DB.Raw("select u.id, u.name, u.realname, u.email,u.status, group_concat(r.name) as role_name"+
		" from users u left join user_roles mhr on u.id = mhr.model_id"+
		"  left join roles r on mhr.role_id = r.id where u.name like ?"+
		"  group by u.id limit ?,?", keywords, page, params.Length).Scan(&result)

	return nil, result
}
